<template>
  <el-tree-select
    v-model="vValue"
    :data="treeData"
    :disabled="disabled"
    :filter-node-method="filterNodeMethod"
    v-bind="attrs"
    @current-change="itemEvent"
  />
</template>
<script setup>
import _ from 'lodash';
import { vModelValue } from '@/utils/hooks.js';
import { apiMethods } from '@/utils/http.js';

const attrs = useAttrs();
const props = defineProps({
  modelValue: {
    type: [String, Array, Number],
    default: '',
  },
  options: {
    // 树值集
    type: Array,
    default: () => [],
  },
  requestUrl: {
    // 请求接口
    type: String,
    default: '',
  },
  tierData: {
    // 调用接口获取数据的层级关系
    type: String,
    default: '',
  },
  // 传参
  params: {
    type: Object,
    default: () => ({}),
  },
  axiosMethod: {
    // 请求方式
    type: String,
    default: 'post',
  },
  cb: {
    // 获取列表之后回调
    type: Function,
  },
});
const emits = defineEmits(['update:modelValue', 'itemEvent']);
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key);
let requestList = ref([]);

onMounted(() => {
  if (props.requestUrl) getDataList();
});

// 下拉值过滤
const treeData = computed(() => {
  let list = [];
  if (props.options?.length) {
    list = [...props.options];
  } else if (props.requestUrl) {
    list = requestList.value;
  }
  return list;
});

// 请求接口
async function getDataList(callback) {
  let res = await apiMethods[props.axiosMethod](props.requestUrl, {
    ...props.params,
  });
  requestList.value = [];
  let arr = null;
  if (props.tierData) {
    let tierArr = props.tierData.split('.');
    tierArr.forEach(item => {
      arr = arr ? arr[item] : res[item];
    });
  } else {
    arr = res.data.data || [];
  }
  requestList.value = arr;
  props.cb && props.cb(arr);
  callback && callback();
}

// 是否禁用
const disabled = computed(() => {
  return attrs.disabledFn && _.isFunction(attrs.disabledFn)
    ? attrs.disabledFn(attrs)
    : attrs.disabled || false;
});

// 过滤
function filterNodeMethod(value, data) {
  return data[attrs.props.label || 'label'].includes(value);
}

// 事件
function itemEvent(data, node) {
  emits('itemEvent', { eventName: 'change', ...attrs, data, node });
}
</script>
